package com.hm.health.records.ecgpatch;

import android.util.Log;

import com.hm.health.Utils.Constans;
import com.hm.health.entity.dao.EcgPatchCsvInfo;
import com.hm.health.entity.dao.EcgPatchSectorInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * 福
 */
public class EcgPatchCsv {

    private final static String TAG = "EcgPatchCsv";

    private final static int RAWDATA_TYPE = 1000;

    private final static int RESULT_TYPE = RAWDATA_TYPE + 1;

    private EcgPatchCsvInfo mCsvInfo;

    private List<EcgPatchSectorInfo> mSectionInfoList = null;

    public EcgPatchCsv(int csvId, long beginTimeStamp, long endTimeStamp, int beginSectorId, int endSectorId, String testId,  List<EcgPatchSectorInfo> sectionInfos) {
        mCsvInfo = new EcgPatchCsvInfo();
        mCsvInfo.setBeginSectorId(beginSectorId);
        mCsvInfo.setEndSectorId(endSectorId);
        mCsvInfo.setBeginTimeStamp(beginTimeStamp);
        mCsvInfo.setEndTimeStamp(endTimeStamp);
        mCsvInfo.setTestId(testId);
        mCsvInfo.setCsvId(csvId);

        String rawdataPath = Constans.ECG_FLASH_DATA_ROOT + testId + "/" + beginTimeStamp + "_" + testId + "_" + csvId + "_" + beginSectorId + "_" + endSectorId + ".csv";
        mCsvInfo.setRawdataFilePath(rawdataPath);

        String resultPath = Constans.ECG_FLASH_RECORD_ROOT + testId + "/" + beginTimeStamp + "_" + testId + "_" + csvId + "_" + beginSectorId + "_" + endSectorId + ".csv";
        mCsvInfo.setResultFilePath(resultPath);

        mSectionInfoList = sectionInfos;

        // 遍历mSectionInfoList，判断这个csv是否需要pc仿真查看算法结果
        boolean hasAlgoResult = true;
        for (int i=0; i<mSectionInfoList.size(); i++) {
            if (!mSectionInfoList.get(i).hasAlgoResult()) {
                // 任意一个sector没有算法结果，整个csv当做没有算法结果处理
                hasAlgoResult = false;
                break;
            }
        }

        mCsvInfo.setHasAlgoResult(hasAlgoResult);

        Log.i(TAG, "new csv:" + mCsvInfo.toString());
    }

    public EcgPatchCsvInfo getCsvInfo() {
        return mCsvInfo;
    }

    private boolean saveDataByType(int type) {

        if (type != RAWDATA_TYPE && type != RESULT_TYPE) {
            Log.e(TAG, "invalid type:" + type);
            return false;
        }

        String path = null;
        if (type == RAWDATA_TYPE) {
            path = mCsvInfo.getRawdataFilePath();
        } else {
            path = mCsvInfo.getResultFilePath();
        }

        File file = new File(path);
        File filePath = file.getParentFile();
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        FileOutputStream outputStream = null;
        try {
            boolean exist = file.createNewFile();
            Log.d(TAG, " create new csv file:" + path + " return:" + exist);
            outputStream = new FileOutputStream(file);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "EXCEPTION:", e);
        }

        EcgPatchSectorInfo info = null;
        BufferedReader reader = null;
        File inputFile = null;
        StringBuilder builder = null;
        String readPath = null;

        for(int i = 0; i < mSectionInfoList.size(); i++) {

            info = mSectionInfoList.get(i);
            builder = new StringBuilder();

            if (type == RAWDATA_TYPE) {
                readPath = info.getSectorFilePath();
            } else {
                readPath = info.getSectorResultFilePath();
            }
            inputFile = new File(readPath);
            try {
                //inputFile.createNewFile();
                reader = new BufferedReader(new FileReader(inputFile));

                String line = null;
                int j =  0;
                while ((line = reader.readLine()) != null) {
                    // i==0, keep csv header
                    if (i != 0 && j < 2) {
                        j++;
                        continue;
                    }

                    builder.append(line).append("\n");
                    j++;
                    if (j % 10 == 0) {
                        outputStream.write(builder.toString().getBytes());
                        builder = new StringBuilder();
                    }
                }

                if (builder.toString().trim().length() > 0) {
                    outputStream.write(builder.toString().getBytes());
                }
                reader.close();

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "IOException:", e);
            }
        }
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    private boolean updateSectorStatus() {

        Log.d(TAG, "updateSectorStatus set regroup flag, sector id from:" + mCsvInfo.getBeginSectorId() + " to " + mCsvInfo.getEndSectorId());
        //EcgPatchSectorInfo info = new EcgPatchSectorInfo();
        //info.setRegroupCSV(true);
        //int ret = info.updateAll("testId = ? and sectorId >= ? and sectorId <= ?",mCsvInfo.getTestId(), Integer.toString(mCsvInfo.getBeginSectorId()), Integer.toString(mCsvInfo.getEndSectorId()));
        //Log.d(TAG, "updateSectorStatus set regroup flag ret " + ret);

        for(int i = 0; i < mSectionInfoList.size(); i++) {
            EcgPatchSectorInfo info = mSectionInfoList.get(i);
            if (!info.isRegroupCSV()) {
                info.setRegroupCSV(true);
                info.save();
            }
        }

        return true;
    }

    private void deleteSectorFile() {
        File file = null;
        boolean delete = false;
        for(int i = 0; i < mSectionInfoList.size(); i++) {
            file = new File(mSectionInfoList.get(i).getSectorFilePath());
            delete = file.delete();
            Log.d(TAG, "delete file:" + mSectionInfoList.get(i).getSectorFilePath() + ", result:" + delete);
            file = new File(mSectionInfoList.get(i).getSectorResultFilePath());
            delete = file.delete();
            Log.d(TAG, "delete file:" + mSectionInfoList.get(i).getSectorResultFilePath() + ", result:" + delete);
        }
    }

    public boolean save() {
        boolean result = false;

        result = saveDataByType(RAWDATA_TYPE);
        Log.d(TAG, "save RAWDATA_TYPE result:" + result);
        if (!result) {
            return result;
        }

        result = saveDataByType(RESULT_TYPE);
        Log.d(TAG, "save RESULT_TYPE result:" + result);
        if (!result) {
            return result;
        }

        result = mCsvInfo.save();
        Log.d(TAG, "save csv db result:" + result);
        if (!result) {
            return result;
        }

        result = updateSectorStatus();
        if (result) {
            Log.d(TAG, "to delete sector cache file belongs to csv which id:" + mCsvInfo.getCsvId());
            deleteSectorFile();
        }

        Log.d(TAG, "[EcgPatchData] save csv id:" + mCsvInfo.getCsvId() + ",result:" + result);
        return result;
    }
}
